<?php

namespace App\Utility\Auth\Wx;

use Exception;

// 处理并返回微信用户信息类
class WxAuth {
	private $config = [ 
			'app_key' => 'wxced6c089dfd379be',
			'app_secret' => '73bd918322f0f504263ee4c603316b1f',
			'scope' => 'snsapi_userinfo',
			'grant_type' => '',
			'callback' => 'http://chat.7b620.cn/AuthLogin/WxLogin/callback',
			'response_type' => '' 
	];
	public function __construct($config) {
		$this->config = $config;
	}
	public function get_code() {
		$this->get_state ();
		$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=';
		$url .= $this->config ['app_key'] . '&redirect_uri=';
		$url .= urlencode ( $this->config ['callback'] );
		$url .= '&response_type=code&scope=' . $this->config ['scope'] . '&state=' . $this->state;
		$url .= '#wechat_redirect';
		return $url;
	}
	
	/**
	 * [get_access_token 获取access_token]
	 *
	 * @param [string] $code
	 *        	[登陆后返回的$_GET['code']]
	 * @return [array] [expires_in 为有效时间 , access_token 为授权码 ; 失败返回 error , error_description ]
	 */
	public function get_access_token($code, $state): AccessTokenBean {
		// $this->is_state ( $state );
		// 获取access_token
		$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->config ['app_key'] . '&secret=' . $this->config ['app_secret'] . '&code=' . $code . '&grant_type=authorization_code';
		$result = json_decode ( $this->_curl_get_content ( $token_url ), true );
		if (isset ( $result ['errcode'] )) {
			throw new Exception ( $result ['errmsg'], $result ['errcode'] );
		}
		return (new AccessTokenBean ( $result ));
	}
	/**
	 * [get_user_info 获取用户信息]
	 *
	 * @param [string] $token
	 *        	[授权码]
	 * @param [string] $openid
	 *        	[用户唯一ID]
	 * @return [array] [ret：返回码，为0时成功。msg为错误信息,正确返回时为空。...params]
	 */
	public function get_user_info(AccessTokenBean $acc): WxUserBean {
		var_dump ( $acc );
		$url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $acc->getAccess_token () . '&openid=' . $acc->getOpenid ();
		$info = json_decode ( $this->_curl_get_content ( $url ), TRUE );
		if (isset ( $info ['errcode"'] )) {
			throw new Exception ( $info ['errmsg'], $info ['errcode'] );
		}
		return (new WxUserBean ( $info ));
	}
	private function _curl_get_content($url) {
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
		curl_setopt ( $ch, CURLOPT_URL, $url );
		// 设置超时时间为3s
		curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 3 );
		$result = curl_exec ( $ch );
		curl_close ( $ch );
		return $result;
	}
	
	// 生成随机参数
	private function get_state() {
		$str = str_shuffle ( 'qazxswedcvfrtgbnhyujmkiol123456789' ) . time ();
		$this->state = $str;
	}
	
	// 判断随机数
	private function is_state($state) {
		$getstate = null;
		if ($state !== $getstate) {
			throw new Exception ( '随机数检验失败，疑似csrf攻击' );
		}
	}
}